from django.shortcuts import render
from django.views import View
from utlis.goods import get_breadcrumb, get_categories, get_goods_specs
from django.http import JsonResponse
from apps.goods.models import SKU, GoodsCategory


class ListView(View):
    """商品列表"""

    def get(self, request, id):
        # 排序字段
        ordering = request.GET.get('ordering')
        # 每页多少条数据
        page_size = request.GET.get('page_size')
        # 要第几页数据
        page = request.GET.get('page')
        try:
            category = GoodsCategory.objects.get(id=id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        # 获取面包屑数据
        brea = get_breadcrumb(category)
        # 查询分类对应的sku数据,排序分页
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)

        # 分页
        from django.core.paginator import Paginator
        # object_list(列表数据) per_page(每页多少条数据)
        paginator = Paginator(skus, per_page=page_size)
        # 获取指定页码数据
        page_skus = paginator.page(page)

        sku_list = []

        for sku in page_skus.object_list:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url
            })

        # 获取总页码
        page_num = paginator.num_pages

        return JsonResponse({'code': 0, 'errmsg': 'ok',
                             'list': sku_list, 'count': page_num,
                             'breadcrumb': brea})


class HotView(View):
    """热销排行"""

    def get(self, request, id):
        skus = SKU.objects.filter(category_id=id, is_launched=True).order_by('-sales')[:2]
        hot_list = []
        for sku in skus:
            hot_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'hot_skus': hot_list})


# *************搜索****************
from haystack.views import SearchView
from django.http import JsonResponse


class SKUSearchView(SearchView):

    # 重写create_response方法
    def create_response(self):
        context = self.get_context()
        sku_list = []
        for sku in context['page'].object_list:
            sku_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count

            })

        return JsonResponse(sku_list, safe=False)


# ********************************************


class DetailView(View):
    """商品详情页"""
    def get(self, request, id):
        try:
            sku = SKU.objects.get(id=id)
        except SKU.DoesNotExist:
            pass
        # 1.分类数据
        categories = get_categories()
        # 2.面包屑
        breadcrumb = get_breadcrumb(sku.category)
        # 3.SKU信息
        # 4.规格信息
        goods_specs = get_goods_specs(sku)

        context = {

            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,

        }
        return render(request, 'detail.html', context)


from apps.goods.models import GoodsVisitCount
class DetailVisitView(View):
    """访问量"""
    def post(self,request,id):
        try:
            category= GoodsCategory.objects.get(id=id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'参数不全'})

        from datetime import date
        today = date.today()

        # 查询有没有这个分类
        try:
            gvc = GoodsVisitCount.objects.get(category=category,date=today)
        # 没有 创建
        except GoodsVisitCount.DoesNotExist:
            GoodsVisitCount.objects.create(
                category=category,
                date=today,
                count=1

            )
        # 有就保存
        else:
            gvc.count+=1
            gvc.save()

        return JsonResponse({'code':0,'errmsg':'ok'})

